﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Threading;
using System.Threading.Tasks; 

namespace BorisTheBlade
{
	public enum RoboMode
	{ 
		rmMonitor,
		//rmMarket,
		rmLimitFromSell,
        rmLimitFromBuy,
        rmLimitTwoWay,
	}

	public partial class mainForm : Form
	{
		
		#region Конструктор

		public mainForm()
		{
			InitializeComponent();
			m_DefCol = this.slotsButton.BackColor;

            this.tradingModeComboBox.SelectedIndex = 0;
			
			this.IsSlotsPanelVisible = false;
			this.IsSecsPanelVisible = false;
			this.IsDispsPanelVisible = false;
			this.IsAveragingPanelVisible = false;

			m_WorkFILoaded = false;
			m_HedjFILoaded = false;

            m_LastWorkSellOrder = new OrderData();
            m_LastWorkBuyOrder = new OrderData();
            m_LastHedjSellOrder = new OrderData();
            m_LastHedjBuyOrder = new OrderData();

            m_BotSettings = new BotSettings();
            LoadSettings(out m_BotSettings);

			//-----------------------------
			// Подключим заполненные данными слоты
			ConnectFilledSlots();
			// Откроем заполненные данными стаканы
			OpenFilledOrderbooks();

            SetTextBoxesEvents();
		}

        private void OpenOrderbookTimer_Tick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(m_BotSettings.WorkSec) && !string.IsNullOrEmpty(m_BotSettings.HedjSec))
            {
                if (m_WorkFILoaded && m_HedjFILoaded && !this.workSecTimer.Enabled && !this.hedjSecTimer.Enabled)
                {
                    this.OpenOrderbookTimer.Stop();
                    this.OpenOrderbookTimer.Enabled = false;
                    AcceptSettings();
                }
            }
        }

        private void SetTextBoxesEvents()
        {
            //-----------------------------
            // Привяжем изменение свойств к изменению цвета
            workLoginTextBox.TextChanged += new EventHandler(workLoginTextBox_TextChanged);
            workPassTextBox.TextChanged += new EventHandler(workPassTextBox_TextChanged);
            workServTextBox.TextChanged += new EventHandler(workServTextBox_TextChanged);
            hedjLoginTextBox.TextChanged += new EventHandler(hedjLoginTextBox_TextChanged);
            hedjPassTextBox.TextChanged += new EventHandler(hedjPassTextBox_TextChanged);
            hedjServTextBox.TextChanged += new EventHandler(hedjServTextBox_TextChanged);

            workSecsСomboBox.TextChanged += new EventHandler(workSecsСomboBox_TextChanged);
            workVolTextBox.TextChanged += new EventHandler(workVolTextBox_TextChanged);
            hedjSecsСomboBox.TextChanged += new EventHandler(hedjSecsСomboBox_TextChanged);
            kHedjTextBox.TextChanged += new EventHandler(kHedjTextBox_TextChanged);

            sellDispTextBox.TextChanged += new EventHandler(sellDispTextBox_TextChanged);
            buyDispTextBox.TextChanged += new EventHandler(buyDispTextBox_TextChanged);

            packageTextBox.TextChanged += new EventHandler(packageTextBox_TextChanged);
            averageTextBox.TextChanged += new EventHandler(averageTextBox_TextChanged);
            maxTextBox.TextChanged += new EventHandler(maxTextBox_TextChanged);
            hotelkaTextBox.TextChanged += new EventHandler(hotelkaTextBox_TextChanged);
            // Привяжем нажатие Enter к сохранению свойств
            workLoginTextBox.KeyDown += new KeyEventHandler(workLoginTextBox_KeyDown);
            workPassTextBox.KeyDown += new KeyEventHandler(workPassTextBox_KeyDown);
            workServTextBox.KeyDown += new KeyEventHandler(workServTextBox_KeyDown);
            hedjLoginTextBox.KeyDown += new KeyEventHandler(hedjLoginTextBox_KeyDown);
            hedjPassTextBox.KeyDown += new KeyEventHandler(hedjPassTextBox_KeyDown);
            hedjServTextBox.KeyDown += new KeyEventHandler(hedjServTextBox_KeyDown);

            workSecsСomboBox.KeyDown += new KeyEventHandler(workSecsСomboBox_KeyDown);
            workVolTextBox.KeyDown += new KeyEventHandler(workVolTextBox_KeyDown);
            hedjSecsСomboBox.KeyDown += new KeyEventHandler(hedjSecsСomboBox_KeyDown);
            kHedjTextBox.KeyDown += new KeyEventHandler(kHedjTextBox_KeyDown);

            sellDispTextBox.KeyDown += new KeyEventHandler(sellDispTextBox_KeyDown);
            buyDispTextBox.KeyDown += new KeyEventHandler(buyDispTextBox_KeyDown);

            packageTextBox.KeyDown += new KeyEventHandler(packageTextBox_KeyDown);
            averageTextBox.KeyDown += new KeyEventHandler(averageTextBox_KeyDown);
            maxTextBox.KeyDown += new KeyEventHandler(maxTextBox_KeyDown);
            hotelkaTextBox.KeyDown += new KeyEventHandler(hotelkaTextBox_KeyDown);

            //new items:
            oporaTextBox.TextChanged += new EventHandler(oporaTextBox_TextChanged);
            beforeHedjTextBox.TextChanged += new EventHandler(beforeHedjTextBox_TextChanged);

            oporaTextBox.KeyDown += new KeyEventHandler(oporaTextBox_KeyDown);
            beforeHedjTextBox.KeyDown += new KeyEventHandler(beforeHedjTextBox_KeyDown);
        }

		private void ConnectFilledSlots()
		{
			if (!string.IsNullOrEmpty(m_BotSettings.WorkLogin) && !string.IsNullOrEmpty(m_BotSettings.WorkPass) && !string.IsNullOrEmpty(m_BotSettings.WorkServ))
				ConnectWork();
			if (!string.IsNullOrEmpty(m_BotSettings.HedjLogin) && !string.IsNullOrEmpty(m_BotSettings.HedjPass) && !string.IsNullOrEmpty(m_BotSettings.HedjServ))
				ConnectHedj();
		}

		private void OpenFilledOrderbooks()
		{

		}

		#region Привяжем нажатие Enter к сохранению свойств

        void beforeHedjTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

        void oporaTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            someTextBox_KeyDown(e);
        }

		void hotelkaTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void maxTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void averageTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void packageTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void buyDispTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void sellDispTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void kHedjTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjSecsСomboBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workVolTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workSecsСomboBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjServTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjPassTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void hedjLoginTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workServTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workPassTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void workLoginTextBox_KeyDown(object sender, KeyEventArgs e)
		{
			someTextBox_KeyDown(e);
		}

		void someTextBox_KeyDown(KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
				AcceptSettings();
		}

		private void AcceptSettings()
		{
			FillSettingsFromForm(out m_BotSettings);
			SetPanelsColor(m_DefCol);
		}

		#endregion Привяжем нажатие Enter к сохранению свойств

		#region Привяжем изменение свойств к изменению цвета

        void beforeHedjTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

        void oporaTextBox_TextChanged(object sender, EventArgs e)
        {
            someTextBox_TextChanged();
        }

		void hotelkaTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void maxTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void averageTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void packageTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void buyDispTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void sellDispTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void kHedjTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjSecsСomboBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workVolTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workSecsСomboBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjServTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjPassTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void hedjLoginTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workServTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workPassTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void workLoginTextBox_TextChanged(object sender, EventArgs e)
		{
			someTextBox_TextChanged();
		}

		void someTextBox_TextChanged()
		{
			SetPanelsColor(Color.Red);
		}

		private void SetPanelsColor(Color color)
		{
			this.slotsPanel.BackColor = this.secsPanel.BackColor = this.dispsPanel.BackColor = this.averagingPanel.BackColor = color;
		}
		
		#endregion Привяжем изменение свойств к изменению цвета
		
		private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
		{
            SaveSettings();
			DisconnectSlots();
		}

		private void DisconnectSlots()
		{
            if (m_WorkConnected)
            {
                ConnectWork();
            }
            if (m_HedjConnected)
            {
                ConnectHedj();
            }
			Thread.Sleep(1000);
            
		}

		#endregion Конструктор

		#region Загрузка и сохранение свойств

		private const string SETTINGSFILENAME = "settings.xml";
		private BotSettings m_BotSettings;

		private void LoadSettings(out BotSettings botSettings)
		{
			if (!File.Exists(SETTINGSFILENAME))
				CreateXMLDocument(SETTINGSFILENAME);
			botSettings = ReadXMLDocument(SETTINGSFILENAME);
			FillFormFromSettings(botSettings);
		}

		private void FillFormFromSettings(BotSettings botSettings)
		{
			if (botSettings == null)
				return;
			// Заполняем поля на форме  
			workLoginTextBox.Text = botSettings.WorkLogin;
			workPassTextBox.Text = botSettings.WorkPass;
			workServTextBox.Text = botSettings.WorkServ;
			hedjLoginTextBox.Text = botSettings.HedjLogin;
			hedjPassTextBox.Text = botSettings.HedjPass;
			hedjServTextBox.Text = botSettings.HedjServ;

			workSecsСomboBox.Text = botSettings.WorkSec;
			workVolTextBox.Text = botSettings.WorkVol;
			hedjSecsСomboBox.Text = botSettings.HedjSec;
			kHedjTextBox.Text = botSettings.KHedj;

			sellDispTextBox.Text = botSettings.SellDisp;
			buyDispTextBox.Text = botSettings.BuyDisp;

			packageTextBox.Text = botSettings.Package;
			averageTextBox.Text = botSettings.Averaging;
			maxTextBox.Text = botSettings.Max;
			hotelkaTextBox.Text = botSettings.Hotelka;

            oporaTextBox.Text = botSettings.Opora;
            beforeHedjTextBox.Text = botSettings.BeforeHedj;
            beforeWorkTextBox.Text = botSettings.BeforeWork;
		}

		private void FillSettingsFromForm(out BotSettings botSettings)
		{
			BotSettings x = new BotSettings();

			x.WorkLogin = workLoginTextBox.Text;
			x.WorkPass = workPassTextBox.Text;
			x.WorkServ = workServTextBox.Text;
			x.HedjLogin = hedjLoginTextBox.Text;
			x.HedjPass = hedjPassTextBox.Text;
			x.HedjServ = hedjServTextBox.Text;

			x.WorkSec = workSecsСomboBox.Text;
			x.WorkVol = (workVolTextBox.Text == string.Empty) ? "0" : workVolTextBox.Text;
			x.HedjSec = hedjSecsСomboBox.Text;
			x.KHedj = (kHedjTextBox.Text == string.Empty) ? "0" : kHedjTextBox.Text;

			x.SellDisp = (sellDispTextBox.Text == string.Empty) ? "0" : sellDispTextBox.Text;
			x.BuyDisp = (buyDispTextBox.Text == string.Empty) ? "0" : buyDispTextBox.Text;

			x.Package = (packageTextBox.Text == string.Empty) ? "0" : packageTextBox.Text;
			x.Averaging = (averageTextBox.Text == string.Empty) ? "0" : averageTextBox.Text;
			x.Max = (maxTextBox.Text == string.Empty) ? "0" : maxTextBox.Text;
			x.Hotelka = (hotelkaTextBox.Text == string.Empty) ? "0" : hotelkaTextBox.Text;

            x.Opora = (oporaTextBox.Text == string.Empty) ? "0" : oporaTextBox.Text;
            x.BeforeHedj = (beforeHedjTextBox.Text == string.Empty) ? "0" : beforeHedjTextBox.Text;
            x.BeforeWork = (beforeWorkTextBox.Text == string.Empty) ? "0" : beforeWorkTextBox.Text;
			
			//------получим бумаги-----
			if (m_WorkConnected && aWorkCon != null && aWorkCon.SecMaster != null && this.workSecsСomboBox.SelectedIndex >= 0)
			{
				string selectedSecCode = this.workSecsСomboBox.Text;
				if (selectedSecCode != string.Empty && selectedSecCode != "Выбрать...")
				{
					//Ищем нужный нам инструмент
					WrapperSecurities sec = aWorkCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
					while (sec == null)
					{
						sec = aWorkCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
						System.Threading.Thread.Sleep(10);
					}
					// Открываем ORDERBOOK для данного инструмента.
					// И подписываемся на ордербук-события.
					if (sec != null && m_BotSettings.WorkSecurity.SecCode != sec.SecCode)
					{
						aWorkCon.OpenTable(WrapperEnums.AllTables.atORDERBOOK, sec.SecBoard, sec.SecCode, "", "");
					}
					x.WorkSecurity = sec;
				}
			}

			if (m_HedjConnected && aHedjCon != null && aHedjCon.SecMaster != null && this.hedjSecsСomboBox.SelectedIndex >= 0)
			{
				string selectedSecCode = this.hedjSecsСomboBox.Text;
				if (selectedSecCode != string.Empty && selectedSecCode != "Выбрать...")
				{
					//Ищем нужный нам инструмент
					WrapperSecurities sec = aHedjCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
					while (sec == null)
					{
						sec = aHedjCon.WSerurities.Find(t => t.ShortName == selectedSecCode);
						System.Threading.Thread.Sleep(10);
					}
					// Открываем ORDERBOOK для данного инструмента.
					// И подписываемся на ордербук-события.
					if (sec != null && m_BotSettings.HedjSecurity.SecCode != sec.SecCode)
					{
						aHedjCon.OpenTable(WrapperEnums.AllTables.atORDERBOOK, sec.SecBoard, sec.SecCode, "", "");
					}
					x.HedjSecurity = sec;
				}
			}

			//----------/////////////////------------------------------
			botSettings = x;
		}

		private void SaveSettings()
		{
			FillSettingsFromForm(out m_BotSettings);
            if (File.Exists(SETTINGSFILENAME))
                File.Delete(SETTINGSFILENAME);
            CreateXMLDocument(SETTINGSFILENAME);
            WriteToXMLDocument(SETTINGSFILENAME, m_BotSettings.WorkLogin, m_BotSettings.WorkPass, m_BotSettings.WorkServ, m_BotSettings.HedjLogin, m_BotSettings.HedjPass, m_BotSettings.HedjServ, m_BotSettings.WorkSec, m_BotSettings.WorkVol, m_BotSettings.HedjSec, m_BotSettings.KHedj, m_BotSettings.SellDisp, m_BotSettings.BuyDisp, m_BotSettings.Package, m_BotSettings.Averaging, m_BotSettings.Max, m_BotSettings.Hotelka, m_BotSettings.Opora, m_BotSettings.BeforeHedj, m_BotSettings.BeforeWork);
		}

        private void WriteToXMLDocument(string filepath, string workLogin, string workPass, string workServ, string hedjLogin, string hedjPass, string hedjServ, string workSec, string workVol, string hedjSec, string kHedj, string sellDisp, string buyDisp, string package, string averaging, string max, string hotelka, string opora, string beforeHedj, string beforeWork)
		{  
			XmlDocument xd = new XmlDocument();
			FileStream fs = new FileStream(filepath, FileMode.Open);
			xd.Load(fs);
            XmlElement setting = xd.DocumentElement["setting"];
            if (setting == null)
                setting = xd.CreateElement("setting");
			setting.SetAttribute("id", "1");
  
			// Создаем 15 полей:
            XmlElement worklogin = xd.DocumentElement["worklogin"]; if (worklogin == null) worklogin = xd.CreateElement("worklogin");

            XmlElement workpass = xd.DocumentElement["workpass"]; if (workpass == null) workpass = xd.CreateElement("workpass");
            XmlElement workserv = xd.DocumentElement["workserv"]; if (workserv == null) workserv = xd.CreateElement("workserv");
            XmlElement hedjlogin = xd.DocumentElement["hedjlogin"]; if (hedjlogin == null) hedjlogin = xd.CreateElement("hedjlogin");
            XmlElement hedjpass = xd.DocumentElement["hedjpass"]; if (hedjpass == null) hedjpass = xd.CreateElement("hedjpass");
            XmlElement hedjserv = xd.DocumentElement["hedjserv"]; if (hedjserv == null) hedjserv = xd.CreateElement("hedjserv");

            XmlElement worksec = xd.DocumentElement["worksec"]; if (worksec == null) worksec = xd.CreateElement("worksec");
            XmlElement workvol = xd.DocumentElement["workvol"]; if (workvol == null) workvol = xd.CreateElement("workvol");
            XmlElement hedjsec = xd.DocumentElement["hedjsec"]; if (hedjsec == null) hedjsec = xd.CreateElement("hedjsec");
            XmlElement khedj = xd.DocumentElement["khedj"]; if (khedj == null) khedj = xd.CreateElement("khedj");

            XmlElement selldisp = xd.DocumentElement["selldisp"]; if (selldisp == null) selldisp = xd.CreateElement("selldisp");
            XmlElement buydisp = xd.DocumentElement["buydisp"]; if (buydisp == null) buydisp = xd.CreateElement("buydisp");

            XmlElement Package = xd.DocumentElement["package"]; if (Package == null) Package = xd.CreateElement("package");
            XmlElement Averaging = xd.DocumentElement["averaging"]; if (Averaging == null) Averaging = xd.CreateElement("averaging");
            XmlElement Max = xd.DocumentElement["max"]; if (Max == null) Max = xd.CreateElement("max");
            XmlElement Hotelka = xd.DocumentElement["hotelka"]; if (Hotelka == null) Hotelka = xd.CreateElement("hotelka");

            XmlElement Opora = xd.DocumentElement["opora"]; if (Opora == null) Opora = xd.CreateElement("opora");
            XmlElement BeforeHedj = xd.DocumentElement["beforeHedj"]; if (BeforeHedj == null) BeforeHedj = xd.CreateElement("beforeHedj");
            XmlElement BeforeWork = xd.DocumentElement["beforeWork"]; if (BeforeWork == null) BeforeWork = xd.CreateElement("beforeWork");

			// Создаем 15 записей
			XmlText tworklogin = xd.CreateTextNode(workLogin);
			XmlText tworkpass = xd.CreateTextNode(workPass);
			XmlText tworkserv = xd.CreateTextNode(workServ);
			XmlText thedjlogin = xd.CreateTextNode(hedjLogin);
			XmlText thedjpass = xd.CreateTextNode(hedjPass);
			XmlText thedjserv = xd.CreateTextNode(hedjServ);

			XmlText tworksec = xd.CreateTextNode(workSec);
			XmlText tworkvol = xd.CreateTextNode(workVol);
			XmlText thedjsec = xd.CreateTextNode(hedjSec);
			XmlText tkhedj = xd.CreateTextNode(kHedj);

			XmlText tselldisp = xd.CreateTextNode(sellDisp);
			XmlText tbuydisp = xd.CreateTextNode(buyDisp);

			XmlText tPackage = xd.CreateTextNode(package);
			XmlText tAveraging = xd.CreateTextNode(averaging);
			XmlText tMax = xd.CreateTextNode(max);
			XmlText tHotelka = xd.CreateTextNode(hotelka);

            XmlText tOpora = xd.CreateTextNode(opora);
            XmlText tBeforeHedj = xd.CreateTextNode(beforeHedj);
            XmlText tBeforeWork = xd.CreateTextNode(beforeWork);

			// Забиваем значения в поля
			worklogin.AppendChild(tworklogin);
			workpass.AppendChild(tworkpass);
			workserv.AppendChild(tworkserv);
			hedjlogin.AppendChild(thedjlogin);
			hedjpass.AppendChild(thedjpass);
			hedjserv.AppendChild(thedjserv);

			worksec.AppendChild(tworksec);
			workvol.AppendChild(tworkvol);
			hedjsec.AppendChild(thedjsec);
			khedj.AppendChild(tkhedj);

			selldisp.AppendChild(tselldisp);
			buydisp.AppendChild(tbuydisp);

			Package.AppendChild(tPackage);
			Averaging.AppendChild(tAveraging);
			Max.AppendChild(tMax);
			Hotelka.AppendChild(tHotelka);

            Opora.AppendChild(tOpora);
            BeforeHedj.AppendChild(tBeforeHedj);
            BeforeWork.AppendChild(tBeforeWork);
	  
			// Забиваем поля в запись Settings
			setting.AppendChild(worklogin);
			setting.AppendChild(workpass);
			setting.AppendChild(workserv);
			setting.AppendChild(hedjlogin);
			setting.AppendChild(hedjpass);
			setting.AppendChild(hedjserv);

			setting.AppendChild(worksec);
			setting.AppendChild(workvol);
			setting.AppendChild(hedjsec);
			setting.AppendChild(khedj);

			setting.AppendChild(selldisp);
			setting.AppendChild(buydisp);

			setting.AppendChild(Package);
			setting.AppendChild(Averaging);
			setting.AppendChild(Max);
			setting.AppendChild(Hotelka);

            setting.AppendChild(Opora);
            setting.AppendChild(BeforeHedj);
            setting.AppendChild(BeforeWork);

			// ЗАбиваем запись в документ  
			xd.DocumentElement.AppendChild(setting);  
  
			fs.Close(); // Закрываем поток  
			xd.Save(filepath); // Сохраняем файл  
		}

		private BotSettings ReadXMLDocument(string filepath)
		{
            string workLogin, workPass, workServ, hedjLogin, hedjPass, hedjServ, workSec, workVol, hedjSec, kHedj, sellDisp, buyDisp, package, averaging, max, hotelka, opora, beforeHedj, beforeWork;
			BotSettings botSettings = new BotSettings();

			// Объявляем и забиваем файл в документ  
			XmlDocument xd = new XmlDocument();
			FileStream fs = new FileStream(filepath, FileMode.Open);
			xd.Load(fs);

			XmlNodeList list = xd.GetElementsByTagName("setting"); // Создаем и заполняем лист по тегу "settings"  
			for (int i = 0; i < list.Count; i++)
			{
				XmlElement id = (XmlElement)xd.GetElementsByTagName("setting")[i];
				XmlElement eworkLogin = (XmlElement)xd.GetElementsByTagName("worklogin")[i];	  // Забиваем login в переменную  
				XmlElement eworkPass = (XmlElement)xd.GetElementsByTagName("workpass")[i];	  // Забиваем login в переменную  
				XmlElement eworkServ = (XmlElement)xd.GetElementsByTagName("workserv")[i];	  // Забиваем login в переменную  
				XmlElement ehedjLogin = (XmlElement)xd.GetElementsByTagName("hedjlogin")[i];	  // Забиваем login в переменную  
				XmlElement ehedjPass = (XmlElement)xd.GetElementsByTagName("hedjpass")[i];	  // Забиваем login в переменную  
				XmlElement ehedjServ = (XmlElement)xd.GetElementsByTagName("hedjserv")[i];	  // Забиваем login в переменную  

				XmlElement eworkSec = (XmlElement)xd.GetElementsByTagName("worksec")[i];	  // Забиваем login в переменную  
				XmlElement eworkVol = (XmlElement)xd.GetElementsByTagName("workvol")[i];	  // Забиваем login в переменную  
				XmlElement ehedjSec = (XmlElement)xd.GetElementsByTagName("hedjsec")[i];	  // Забиваем login в переменную  
				XmlElement ekHedj = (XmlElement)xd.GetElementsByTagName("khedj")[i];	  // Забиваем login в переменную  

				XmlElement esellDisp = (XmlElement)xd.GetElementsByTagName("selldisp")[i];	  // Забиваем login в переменную  
				XmlElement ebuyDisp = (XmlElement)xd.GetElementsByTagName("buydisp")[i];	  // Забиваем login в переменную  

				XmlElement epackage = (XmlElement)xd.GetElementsByTagName("package")[i];	  // Забиваем login в переменную  
				XmlElement eaveraging = (XmlElement)xd.GetElementsByTagName("averaging")[i];	  // Забиваем login в переменную  
				XmlElement emax = (XmlElement)xd.GetElementsByTagName("max")[i];	  // Забиваем login в переменную  
				XmlElement ehotelka = (XmlElement)xd.GetElementsByTagName("hotelka")[i];	  // Забиваем login в переменную  

                XmlElement eopora = (XmlElement)xd.GetElementsByTagName("opora")[i];	  // Забиваем login в переменную  
                XmlElement ebeforeHedj = (XmlElement)xd.GetElementsByTagName("beforeHedj")[i];	  // Забиваем login в переменную  
                XmlElement ebeforeWork = (XmlElement)xd.GetElementsByTagName("beforeWork")[i];	  // Забиваем login в переменную  

				// Вставляем в переменные текст из тегов  
				if (id.GetAttribute("id") == "1")
				{
					workLogin = eworkLogin.InnerText;
					workPass = eworkPass.InnerText;
					workServ = eworkServ.InnerText;
					hedjLogin = ehedjLogin.InnerText;
					hedjPass = ehedjPass.InnerText;
					hedjServ = ehedjServ.InnerText;
					workSec = eworkSec.InnerText;

					workVol = eworkVol.InnerText;
					hedjSec = ehedjSec.InnerText;
					kHedj = ekHedj.InnerText;

					sellDisp = esellDisp.InnerText;
					buyDisp = ebuyDisp.InnerText;

					package = epackage.InnerText;
					averaging = eaveraging.InnerText;
					max = emax.InnerText;
					hotelka = ehotelka.InnerText;

                    opora = (eopora == null || string.IsNullOrEmpty(eopora.InnerText)) ? "0" : eopora.InnerText;
                    beforeHedj = (ebeforeHedj == null || string.IsNullOrEmpty(ebeforeHedj.InnerText)) ? "0" : ebeforeHedj.InnerText;
                    beforeWork = (ebeforeWork == null || string.IsNullOrEmpty(ebeforeWork.InnerText)) ? "0" : ebeforeWork.InnerText;

					// Заполняем поля настроек
					botSettings.WorkLogin = workLogin;
					botSettings.WorkPass = workPass;
					botSettings.WorkServ = workServ;
					botSettings.HedjLogin = hedjLogin;
					botSettings.HedjPass = hedjPass;
					botSettings.HedjServ = hedjServ;

					botSettings.WorkSec = workSec;
					botSettings.WorkVol = workVol;
					botSettings.HedjSec = hedjSec;
					botSettings.KHedj = kHedj;

					botSettings.SellDisp = sellDisp;
					botSettings.BuyDisp = buyDisp;

					botSettings.Package = package;
					botSettings.Averaging = averaging;
					botSettings.Max = max;
					botSettings.Hotelka = hotelka;

                    botSettings.Opora = opora;
                    botSettings.BeforeHedj = beforeHedj;
                    botSettings.BeforeWork = beforeWork;
				}
			}
			// Закрываем поток  
			fs.Close();
			return botSettings;
		} 

		private void CreateXMLDocument(string filepath)
		{
			XmlTextWriter xtw = new XmlTextWriter(filepath, Encoding.UTF8);
			xtw.WriteStartDocument();
			xtw.WriteStartElement("settings");
			xtw.WriteEndDocument();
			xtw.Close();
		}

		#endregion Загрузка и сохранение свойств

		#region Показ и скрытие панелей

		public bool IsSlotsPanelVisible { get { return slotsPanel.Visible; } set { slotsPanel.Visible = value; if (value) slotsButton.BackColor = Color.Yellow; else slotsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsSecsPanelVisible { get { return secsPanel.Visible; } set { secsPanel.Visible = value; if (value) secsButton.BackColor = Color.Yellow; else secsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsDispsPanelVisible { get { return dispsPanel.Visible; } set { dispsPanel.Visible = value; if (value) dispsButton.BackColor = Color.Yellow; else dispsButton.BackColor = m_DefCol; SetPanelsPositions(); } }
		public bool IsAveragingPanelVisible { get { return averagingPanel.Visible; } set { averagingPanel.Visible = value; if (value) averagingButton.BackColor = Color.Yellow; else averagingButton.BackColor = m_DefCol; SetPanelsPositions(); } }

		public enum PanelsPriority
		{
			ppSlotsPanel = 50,
			ppSecsPanel = 100,
			ppDispsPanel = 150,
			ppAvaredgingPanel = 200,
		}

		private Color m_DefCol;

		private void SetPanelsPositions()
		{
			slotsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible)
				secsPanel.Top = (int)PanelsPriority.ppSecsPanel;
			else
				secsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible && IsSecsPanelVisible)
				dispsPanel.Top = (int)PanelsPriority.ppDispsPanel;
			else
				if (IsSlotsPanelVisible || IsSecsPanelVisible)
					dispsPanel.Top = (int)PanelsPriority.ppSecsPanel;
				else
					dispsPanel.Top = (int)PanelsPriority.ppSlotsPanel;
			//------------
			if (IsSlotsPanelVisible && IsSecsPanelVisible && IsDispsPanelVisible)
				averagingPanel.Top = (int)PanelsPriority.ppAvaredgingPanel;
			else
				if ((IsSlotsPanelVisible && IsSecsPanelVisible) || (IsSlotsPanelVisible && IsDispsPanelVisible) || (IsSecsPanelVisible && IsDispsPanelVisible))
				{
					if (IsDispsPanelVisible)
						averagingPanel.Top = (int)PanelsPriority.ppDispsPanel;
					else
						averagingPanel.Top = (int)PanelsPriority.ppDispsPanel;
				}
				else
					if (IsSlotsPanelVisible || IsSecsPanelVisible || IsDispsPanelVisible)
						averagingPanel.Top = (int)PanelsPriority.ppSecsPanel;
					else
						averagingPanel.Top = (int)PanelsPriority.ppSlotsPanel;

		}

		private void slotsButton_Click(object sender, EventArgs e)
		{
			if (this.IsSlotsPanelVisible) 
				this.IsSlotsPanelVisible = false;
			else
				this.IsSlotsPanelVisible = true;
		}

		private void secsButton_Click(object sender, EventArgs e)
		{
			if (this.IsSecsPanelVisible)
				this.IsSecsPanelVisible = false;
			else
				this.IsSecsPanelVisible = true;
		}

		private void dispsButton_Click(object sender, EventArgs e)
		{
			if (this.IsDispsPanelVisible)
				this.IsDispsPanelVisible = false;
			else
				this.IsDispsPanelVisible = true;
		}

		private void averagingButton_Click(object sender, EventArgs e)
		{
			if (this.IsAveragingPanelVisible)
				this.IsAveragingPanelVisible = false;
			else
				this.IsAveragingPanelVisible = true;
		}

		RoboMode curMode = RoboMode.rmMonitor;
		private void tradingModeComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			switch (tradingModeComboBox.SelectedIndex)
			{
				case 0: curMode = RoboMode.rmMonitor; break;
				case 1: curMode = RoboMode.rmLimitFromSell; break;
				case 2: curMode = RoboMode.rmLimitTwoWay; break;
                case 3: curMode = RoboMode.rmLimitFromBuy; break;

				default:
					break;
			}
			if (this.tradingModeComboBox.SelectedIndex > 0)
			{
				this.IsSlotsPanelVisible = this.IsSecsPanelVisible = this.IsDispsPanelVisible = this.IsAveragingPanelVisible = false;
				this.mainPanel.Height = 24;
			}
			else
				this.mainPanel.Height = 48;
		}
		#endregion Показ и скрытие панелей

		#region Подключение рабочего

		private AtentisWrapper aWorkWrap;
		private AtentisConnection aWorkCon;
		private bool m_WorkConnected = false;
		private bool m_WorkFILoaded;

		private void connectWorkButton_Click(object sender, EventArgs e)
		{
			ConnectWork();
		}

        private bool m_WorkSyncronized = false;

		private void ConnectWork()
		{
			if (!this.m_WorkConnected)
			{
				AcceptSettings();

				aWorkWrap = new AtentisWrapper();
				aWorkCon = (AtentisConnection)aWorkWrap.AddConnection("DataSlot", m_BotSettings.WorkServ, m_BotSettings.WorkLogin, m_BotSettings.WorkPass);
				/*
				aWorkCon.Connected += aWorkCon_Connected;
				aWorkCon.SecMaster.HasNewTrade += SecMaster_HasNewTrade;
				*/
				aWorkCon.SecMaster.FILoaded += SecMaster_WorkFILoaded;
				aWorkCon.SecMaster.SellOrderComplete += SecMaster_WorkSellOrderComplete;
				aWorkCon.SecMaster.BuyOrderComplete += SecMaster_WorkBuyOrderComplete;
				aWorkCon.SecMaster.PositionsUpdated += SecMaster_WorkPositionsUpdated;
				aWorkCon.SecMaster.HoldingsUpdated += SecMaster_WorkHoldingsUpdated;
				aWorkCon.SecMaster.OrderbookUpdated += SecMaster_WorkOrderbookUpdated;
                aWorkCon.SecMaster.OrderbookReplBegin += SecMaster_WorkOrderbookReplBegin;
                aWorkCon.SecMaster.OrderbookReplEnd += SecMaster_WorkOrderbookReplEnd;

				OpenTables(aWorkCon);

				aWorkCon.Connect();
				aWorkCon.RefreshFreq = 1;
                //aWorkCon.Connected += new EventHandler(aWorkWrap_Synchronized);
                aWorkWrap.Synchronized +=new EventHandler(aWorkWrap_Synchronized);
                while (!m_WorkSyncronized) Thread.Sleep(10);

				m_WorkConnected = true;
				this.connectWorkButton.Text = "Отключить";

			}
			else
			{
				aWorkCon.Disconnect();
				m_WorkConnected = false;
				this.workSecsСomboBox.Items.Clear();
				this.workSecsСomboBox.Text = string.Empty;
				this.connectWorkButton.Text = "Подключить";
			}
		}

        void aWorkWrap_Synchronized(object sender, EventArgs e)
        {
            m_WorkSyncronized = true;
        }

		void SecMaster_WorkFILoaded(object sender, EventArgs e)
		{
			m_WorkFILoaded = true;
		}

		private void workSecTimer_Tick(object sender, EventArgs e)
		{
			if (m_WorkFILoaded && aWorkCon != null && aWorkCon.WSerurities != null && aWorkCon.WSerurities.Count() > 1)
			{
				//var count = aCon.WFirm_Holding_Total.Count();
				var count = aWorkCon.WSerurities.Count();
				for (int i = 0; i < count; i++)
				{
					//var elem = aCon.WFirm_Holding_Total[i];
					var elem = aWorkCon.WSerurities[i];
					if (elem != null) this.workSecsСomboBox.Items.Add(elem.ShortName);
				}
				//this.workSecsСomboBox.SelectedIndex = 1;
				int pos = this.workSecsСomboBox.Items.IndexOf(this.workSecsСomboBox.Text);
				if (this.workSecsСomboBox.Text != "Выбрать..." && this.workSecsСomboBox.Text != "")
					this.workSecsСomboBox.SelectedIndex = pos;
				else
					this.workSecsСomboBox.Text = "Выбрать...";

				this.workSecTimer.Stop();
				this.workSecTimer.Enabled = false;
			}
		}

		void SecMaster_WorkSellOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
				if (row != null)
				{
					var trdRow = row.WrapperTradesRow;
					if (trdRow.OrderNo == m_LastWorkSellOrder.OrderNo)
					{
                        m_LastWorkSellOrder.Amount -= trdRow.Quantity;
                        HedjLastSell(trdRow.Quantity);
					}
				}
			}
		}

		void SecMaster_WorkBuyOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
				if (row != null)
				{
					var trdRow = row.WrapperTradesRow;
                    if (trdRow.OrderNo == m_LastWorkBuyOrder.OrderNo)
                    {
                        m_LastWorkBuyOrder.Amount -= trdRow.Quantity;
                        HedjLastBuy(trdRow.Quantity);
                    }
				}
			}
		}

		void SecMaster_WorkPositionsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{

			}
		}

		private int m_ConCount = 0;
		void SecMaster_WorkHoldingsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
                PerformDisp();
			}
		}

        private void GetConCount()
        {
            if (aWorkCon == null) return;
            if (aWorkCon.WFirm_Holding_Total != null && aWorkCon.WFirm_Holding_Total.Count > 0)
            {
                if (m_BotSettings.WorkSecurity != null)
                {
                    var p = aWorkCon.WFirm_Holding_Total.Find(x => x.SecCode == m_BotSettings.WorkSecurity.SecCode);
                    if (p != null)
                        m_ConCount = (int)p.CurrentPos;
                }
            }

            if (aHedjCon == null) return;
            if (aHedjCon.WFirm_Holding_Total != null && aHedjCon.WFirm_Holding_Total.Count > 0)
            {
                if (m_BotSettings.HedjSecurity != null)
                {
                    var p = aHedjCon.WFirm_Holding_Total.Find(x => x.SecCode == m_BotSettings.HedjSecurity.SecCode);
                    if (p != null)
                        m_HedjConCount = (int)p.CurrentPos;
                }
            }
        }


		private static void OpenTables(AtentisConnection con)
		{

			con.OpenTable(WrapperEnums.AllTables.atSECURITIES, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atINDEXES, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atBOARDS, "", "");
			con.OpenTable(WrapperEnums.AllTables.atFIRM_HOLDING_TOTAL, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atHISTORY, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atHISTORY_DAILY, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atNEWS, "", "");

			con.OpenTable(WrapperEnums.AllTables.atORDERS, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atPOSITIONS, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atSTOPORDERS, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atTESYSTIME, "", "");
			con.OpenTable(WrapperEnums.AllTables.atTRADES, "", "");
			con.OpenTable(WrapperEnums.AllTables.atTRDACC, "", "");
			//con.OpenTable(WrapperEnums.AllTables.atALL_TRADES, "", "");

			//********
		}

		#endregion Подключение рабочего

		#region Подключение хеджера

		private AtentisWrapper aHedjWrap;
		private AtentisConnection aHedjCon;
		private bool m_HedjConnected = false;
		private bool m_HedjFILoaded;

		private void connectHedjButton_Click(object sender, EventArgs e)
		{
			ConnectHedj();
		}

        private bool m_HedjSyncronized = false;

		private void ConnectHedj()
		{
			if (!this.m_HedjConnected)
			{
				AcceptSettings();

				aHedjWrap = new AtentisWrapper();
				aHedjCon = (AtentisConnection)aHedjWrap.AddConnection("DataSlot", m_BotSettings.HedjServ, m_BotSettings.HedjLogin, m_BotSettings.HedjPass);
				/*
				aHedjCon.Connected += aHedjCon_Connected;
				aHedjCon.SecMaster.HasNewTrade += SecMaster_HasNewTrade;
				*/
				aHedjCon.SecMaster.FILoaded += SecMaster_HedjFILoaded;
				aHedjCon.SecMaster.SellOrderComplete += SecMaster_HedjSellOrderComplete;
				aHedjCon.SecMaster.BuyOrderComplete += SecMaster_HedjBuyOrderComplete;
				aHedjCon.SecMaster.PositionsUpdated += SecMaster_HedjPositionsUpdated;
				aHedjCon.SecMaster.OrderbookUpdated += SecMaster_HedjOrderbookUpdated;
                aHedjCon.SecMaster.OrderbookReplBegin += SecMaster_HedjOrderbookReplBegin;
                aHedjCon.SecMaster.OrderbookReplEnd += SecMaster_HedjOrderbookReplEnd;
                aHedjCon.SecMaster.HoldingsUpdated += SecMaster_HedjHoldingsUpdated;

				OpenTables(aHedjCon);

				aHedjCon.Connect();
				aHedjCon.RefreshFreq = 1;

                //aHedjCon.Connected += new EventHandler(aHedjWrap_Synchronized);
                aHedjWrap.Synchronized += new EventHandler(aHedjWrap_Synchronized);
                while (!m_HedjSyncronized) Thread.Sleep(10);

				m_HedjConnected = true;
				this.connectHedjButton.Text = "Отключить";

			}
			else
			{
				aHedjCon.Disconnect();
				m_HedjConnected = false;
				this.hedjSecsСomboBox.Items.Clear();
				this.hedjSecsСomboBox.Text = string.Empty;
				this.connectHedjButton.Text = "Подключить";
			}
		}

        private int m_HedjConCount = 0;
        void SecMaster_HedjHoldingsUpdated(object sender, EventArgs e)
        {
            if (e is AtentisConnectorEventArgs)
            {
                PerformDisp();
            }
        }

        void aHedjWrap_Synchronized(object sender, EventArgs e)
        {
            m_HedjSyncronized = true;
        }

		void SecMaster_HedjFILoaded(object sender, EventArgs e)
		{
			m_HedjFILoaded = true;
		}

		private void hedjSecTimer_Tick(object sender, EventArgs e)
		{
			if (m_HedjFILoaded && aHedjCon != null && aHedjCon.WSerurities != null && aHedjCon.WSerurities.Count() > 1)
			{
				//var count = aCon.WFirm_Holding_Total.Count();
				var count = aHedjCon.WSerurities.Count();
				for (int i = 0; i < count; i++)
				{
					//var elem = aCon.WFirm_Holding_Total[i];
					var elem = aHedjCon.WSerurities[i];
					if (elem != null) this.hedjSecsСomboBox.Items.Add(elem.ShortName);
				}
				//this.hedjSecsСomboBox.SelectedIndex = 1;
				int pos = this.hedjSecsСomboBox.Items.IndexOf(this.hedjSecsСomboBox.Text);
				if (this.hedjSecsСomboBox.Text != "Выбрать..." && this.hedjSecsСomboBox.Text != "")
					this.hedjSecsСomboBox.SelectedIndex = pos;
				else
					this.hedjSecsСomboBox.Text = "Выбрать...";

				this.hedjSecTimer.Stop();
				this.hedjSecTimer.Enabled = false;
			}
		}

		void SecMaster_HedjSellOrderComplete(object sender, EventArgs e)
		{
            if (e is AtentisConnectorEventArgs)
            {
                var row = e as AtentisConnectorEventArgs;
                if (row != null)
                {
                    var trdRow = row.WrapperTradesRow;
                    if (trdRow.OrderNo == m_LastHedjSellOrder.OrderNo)
                    {
                        m_LastHedjSellOrder.Amount -= trdRow.Quantity;
                        if (m_LastHedjSellOrder.Amount == 0)
                        {
                            m_MayInBuy = false;
                            m_BuyHedjTime = false;
                        }
                    }
                }
            }
		}

		void SecMaster_HedjBuyOrderComplete(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var row = e as AtentisConnectorEventArgs;
				if (row != null)
				{
					var trdRow = row.WrapperTradesRow;
					if (trdRow.OrderNo == m_LastHedjBuyOrder.OrderNo)
					{
						m_LastHedjBuyOrder.Amount -= trdRow.Quantity;
                        if (m_LastHedjBuyOrder.Amount == 0)
                        {
                            m_MayInSell = false;
                            m_SellHedjTime = false;
                        }
					}
				}
			}
		}

		void SecMaster_HedjPositionsUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{

			}
		}

		#endregion Подключение хеджера

		#region Выбор рабочего

		private void workSecsСomboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
//
		}

		#endregion Выбор рабочего

		#region Выбор хеджера

		private void hedjSecsСomboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
//
		}

		#endregion Выбор хеджера

		#region Обработка стакана рабочего

		WrapperOrderbook m_WorkLastRow = new WrapperOrderbook();
		double m_WorkBestBuy = 0;
		double m_WorkBestSell = 0;

        List<WrapperOrderbook> m_WorkOrderbook = new List<WrapperOrderbook>();


        void SecMaster_WorkOrderbookReplBegin(object sender, EventArgs e)
        {
            //
        }

        void SecMaster_WorkOrderbookReplEnd(object sender, EventArgs e)
        {
            ProcessWorkStakan();
        }

        void SecMaster_WorkOrderbookUpdated(object sender, EventArgs e)
		{
			if (e is AtentisConnectorEventArgs)
			{
				var dr = e as AtentisConnectorEventArgs;
				var row = dr.WrapperOrderbookRow;
                m_WorkOrderbook.Add(row);
			}
		}

        private int m_BeforeWorkSellVol = 0;
        private int m_BeforeWorkBuyVol = 0;

        private void ProcessWorkStakan()
        {


            m_BeforeWorkSellVol = -1;
            m_BeforeWorkBuyVol = -1;

            m_WorkBestBuy = -1;
            m_WorkBestSell = -1;

            int buyIndex = 0;
            int sellIndex = 0;

            for (int i = 0; i < m_WorkOrderbook.Count - 1; i++)
            {
                var row = m_WorkOrderbook[i];
                if (row.BuySell == "B" && m_WorkOrderbook[i + 1].BuySell == "S")
                {
                    buyIndex = i;
                    sellIndex = i + 1;
                    break;
                }
            }
            m_WorkBestBuy = m_WorkOrderbook[buyIndex].Price;
            m_WorkBestSell = m_WorkOrderbook[sellIndex].Price;

            
            int buyVol = 0;
            //ищем лучшую цену покупки спота с учетом опорника
            for (int i = buyIndex; i >= 0; i--)
            {
                var row = m_WorkOrderbook[i];
                buyVol += row.Quantity;
                if (m_WorkBestBuy < 0 && buyVol >= m_BotSettings.IntOpora)
                    m_WorkBestBuy = row.Price;
                if (m_LastWorkBuyOrder.Price > 0)
                {
                    if (m_LastWorkBuyOrder.Price <= row.Price)
                        m_BeforeWorkBuyVol = buyVol;
                }
                else
                    if (m_WorkBestBuy > 0) break;

            }

            int sellVol = 0;
            //ищем лучшую цену продажи спота с учетом опорника
            for (int i = sellIndex; i < m_WorkOrderbook.Count - 1; i++)
            {
                var row = m_WorkOrderbook[i];
                sellVol += row.Quantity;
                if (m_WorkBestSell < 0 && sellVol >= m_BotSettings.IntOpora)
                    m_WorkBestSell = row.Price;
                if (m_LastWorkSellOrder.Price > 0)
                {
                    if (m_LastWorkSellOrder.Price >= row.Price)
                        m_BeforeWorkSellVol = sellVol;
                }
                else
                    if (m_WorkBestSell > 0) break;
            }

            m_WorkOrderbook.Clear();
            ProcessDisps(m_WorkBestBuy, m_WorkBestSell, m_HedjBestBuy, m_HedjBestSell);
        }

		#endregion Обработка стакана рабочего

		#region Обработка стакана хеджера

        void SecMaster_HedjOrderbookReplBegin(object sender, EventArgs e)
        {
            //
        }

        void SecMaster_HedjOrderbookReplEnd(object sender, EventArgs e)
        {
            ProcessHedjStakan();
        }

		WrapperOrderbook m_HedjLastRow = new WrapperOrderbook();
		double m_HedjBestBuy = 0;
		double m_HedjBestSell = 0;

        private List<WrapperOrderbook> m_HedjOrderbook = new List<WrapperOrderbook>();

        private int m_BeforeSellVol = 0;
        private int m_BeforeBuyVol = 0;

		void SecMaster_HedjOrderbookUpdated(object sender, EventArgs e)
		{
            if (e is AtentisConnectorEventArgs)
            {
                var dr = e as AtentisConnectorEventArgs;
                var row = dr.WrapperOrderbookRow;
                m_HedjOrderbook.Add(row);
            }
		}

        private void ProcessHedjStakan()
        {
            m_BeforeSellVol = -1;
            m_BeforeBuyVol = -1;

            m_HedjBestBuy = -1;
            m_HedjBestSell = -1;

            int buyIndex = 0;
            int sellIndex = 0;

            for (int i = 0; i < m_HedjOrderbook.Count-1; i++)
            {
                var row = m_HedjOrderbook[i];
                if (row.BuySell == "B" && m_HedjOrderbook[i+1].BuySell == "S")
                {
                    buyIndex = i;
                    sellIndex = i+1;
                    break;
                }
            }

            int buyVol = 0;
            //ищем лучшую цену покупки спота с учетом опорника
            for (int i = buyIndex; i >=0; i--)
            {
                var row = m_HedjOrderbook[i];
                buyVol += row.Quantity;
                if (m_HedjBestBuy < 0 && buyVol >= m_BotSettings.IntOpora)
                    m_HedjBestBuy = row.Price;
                if (m_LastHedjSellOrder.Price > 0)
                {
                    if (m_LastHedjSellOrder.Price >= row.Price)
                        m_BeforeBuyVol = buyVol;
                }
                else
                    if (m_HedjBestBuy > 0) break;

            }

            int sellVol = 0;
            //ищем лучшую цену продажи спота с учетом опорника
            for (int i = sellIndex; i < m_HedjOrderbook.Count - 1; i++)
            {
                var row = m_HedjOrderbook[i];
                sellVol += row.Quantity;
                if (m_HedjBestSell < 0 && sellVol >= m_BotSettings.IntOpora)
                    m_HedjBestSell = row.Price;
                if (m_LastHedjBuyOrder.Price > 0)
                {
                    if (m_LastHedjBuyOrder.Price <= row.Price)
                        m_BeforeSellVol = sellVol;
                }
                else
                    if (m_HedjBestSell > 0) break;
            }

            m_HedjOrderbook.Clear();
            ProcessDisps(m_WorkBestBuy, m_WorkBestSell, m_HedjBestBuy, m_HedjBestSell);
        }

		#endregion Обработка стакана хеджера

		#region Расчет раздвижек
		private double m_SellDisp = 0;
		private double m_BuyDisp = 0;
        object locker = new object();
		private void ProcessDisps(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{
            lock (locker)
            {
                if (hedjBestBuy < 0 || hedjBestSell < 0 || workBestBuy < 0 || workBestSell < 0)
                    return;

                m_SellDisp = workBestSell - hedjBestSell * (double)m_BotSettings.FloatKHedj;
                m_BuyDisp = -(hedjBestBuy * (double)m_BotSettings.FloatKHedj - workBestBuy);

                // Проверим - можно ли продавать/покупать

                // Двусторонний
                if (curMode != RoboMode.rmMonitor)
                {
                    if (!m_MayInBuy) CheckChanceForSell(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                    if (!m_MayInSell) CheckChanceForBuy(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                }
                // Дохеджим рынок
                if (curMode == RoboMode.rmMonitor && (m_SellHedjTime || m_BuyHedjTime))
                {
                    if (!m_MayInBuy) CheckChanceForSell(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                    if (!m_MayInSell) CheckChanceForBuy(workBestBuy, workBestSell, hedjBestBuy, hedjBestSell);
                }
                /*
                this.SetPropertyThreadSafe(() => curSellDispLabel.Text, m_SellDisp.ToString());
                this.SetPropertyThreadSafe(() => curBuyDispLabel.Text, m_BuyDisp.ToString());
                */
            }
		}

		private OrderData m_LastWorkSellOrder;
		private OrderData m_LastWorkBuyOrder;
		private OrderData m_LastHedjSellOrder;
		private OrderData m_LastHedjBuyOrder;

		private bool m_MayInSell = false;
		private bool m_MayInBuy = false;

        private void CheckChanceForSell(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{
			if (m_SellDisp > m_NextSellDisp && !m_MayInSell)
			{
				// можно продавать
                DoSell(workBestSell-1);
			}
            // Раздвижка ушла - снимаем фортс
            if (m_SellDisp <= m_NextSellDisp-1 && m_MayInSell && !m_SellHedjTime)
            {
                if (aWorkCon.DelOrder(m_LastWorkSellOrder.OrderNo))
                    m_MayInSell = false;
            }

            // Встал объем впереди хеджера - переставляем спот как по-рынку
            //if (m_SellDisp <= m_NextSellDisp && m_MayInSell && m_SellHedjTime)
            if (m_BeforeSellVol > m_BotSettings.IntBeforeHedj && m_MayInSell && m_SellHedjTime)
            {
                if (aHedjCon.DelOrder(m_LastHedjBuyOrder.OrderNo))
                {
                    string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string mktLimit = "L";
                    double price = hedjBestSell;
                    long outOrderNo = 0;
                    string outResMsg = string.Empty;
                    string secBoard = m_BotSettings.HedjSecurity.SecBoard;
                    string secCode = m_BotSettings.HedjSecurity.SecCode;
                    int res = aHedjCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, m_LastHedjBuyOrder.Amount, extRef, out outOrderNo, out outResMsg);
                    if (outOrderNo > 0)
                    {
                        m_LastHedjBuyOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                        //m_SellHedjTime = false;
                    }
                }

            }
            // Делаем MoveOrder
            if (m_SellDisp > m_NextSellDisp && m_MayInSell && m_BeforeWorkSellVol > m_BotSettings.IntBeforeWork)
            {
                // можно продавать
                if (m_LastWorkSellOrder.MktLimit == "L" && m_LastWorkSellOrder.Price > workBestSell)
                {
                    string extRef = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string extRef2 = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    long outOrderNo1 = 0;
                    long outOrderNo2 = 0;
                    string outResMsg = string.Empty;
                    int res = aWorkCon.MoveOrder(2, m_LastWorkSellOrder.OrderNo, workBestSell - 1, m_LastWorkSellOrder.Amount, extRef, 0, 0, 0, extRef2, out outOrderNo1, out outOrderNo2, outResMsg);
                    if (outOrderNo1 > 0)
                    {
                        m_LastWorkSellOrder = aWorkCon.OrderDatas.GetData(outOrderNo1);
                    }
                }
            }
		}

		private void DoSell(double price)
		{
            m_MayInSell = true;
            string extRef = string.Empty; // m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
			int vol = m_NextSellVol;
			long outOrderNo = 0;
			string outResMsg = string.Empty;
			string secBoard = m_BotSettings.WorkSecurity.SecBoard;
			string secCode = m_BotSettings.WorkSecurity.SecCode;
            if (vol > 0 && price > 0)
            {
                int res = aWorkCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                if (outOrderNo > 0)
                {
                    m_LastWorkSellOrder = aWorkCon.OrderDatas.GetData(outOrderNo);
                }
                else
                    m_MayInSell = false;
            }
            else
                m_MayInSell = false;
		}

        private bool m_SellHedjTime = false;
		private void HedjLastSell(int vol)
		{
            string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
			string mktLimit = "L";
			double price = (m_LastWorkSellOrder.Price - m_NextSellDisp) / (double)m_BotSettings.FloatKHedj;
			long outOrderNo = 0;
			string outResMsg = string.Empty;
			string secBoard = m_BotSettings.HedjSecurity.SecBoard;
			string secCode = m_BotSettings.HedjSecurity.SecCode;
            int realVol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * vol;
            int res = aHedjCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, realVol, extRef, out outOrderNo, out outResMsg);
			if (outOrderNo > 0)
			{
				m_LastHedjBuyOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                m_SellHedjTime = true;
			}
		}

        private void CheckChanceForBuy(double workBestBuy, double workBestSell, double hedjBestBuy, double hedjBestSell)
		{
            if (m_BuyDisp < m_NextBuyDisp && !m_MayInBuy)
			{
				// можно покупать
                DoBuy(workBestBuy+1);
			}
            // Раздвижка ушла - снимаем фортс
            if (m_BuyDisp >= m_NextBuyDisp+1 && m_MayInBuy && !m_BuyHedjTime)
            {
                if (aWorkCon.DelOrder(m_LastWorkBuyOrder.OrderNo))
                    m_MayInBuy = false;
            }
            // Пришел объем больше чем объем впереди хеджера - переставляем спот как по-рынку
            if (m_BeforeBuyVol > m_BotSettings.IntBeforeHedj && m_MayInBuy && m_BuyHedjTime)
            {
                if (aHedjCon.DelOrder(m_LastHedjSellOrder.OrderNo))
                {
                    string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string mktLimit = "L";
                    double price = hedjBestBuy;
                    long outOrderNo = 0;
                    string outResMsg = string.Empty;
                    string secBoard = m_BotSettings.HedjSecurity.SecBoard;
                    string secCode = m_BotSettings.HedjSecurity.SecCode;
                    int res = aHedjCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, m_LastHedjSellOrder.Amount, extRef, out outOrderNo, out outResMsg);
                    if (outOrderNo > 0)
                    {
                        m_LastHedjSellOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                        //m_BuyHedjTime = false;
                    }
                }

            }
            // Делаем MoveOrder
            if (m_BuyDisp < m_NextBuyDisp && m_MayInBuy && m_BeforeWorkBuyVol > m_BotSettings.IntBeforeWork)
            {
                // можно продавать
                if (m_LastWorkBuyOrder.MktLimit == "L" && m_LastWorkBuyOrder.Price < workBestBuy)
                {
                    string extRef = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    string extRef2 = string.Empty; //m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
                    long outOrderNo1 = 0;
                    long outOrderNo2 = 0;
                    string outResMsg = string.Empty;
                    int res = aWorkCon.MoveOrder(2, m_LastWorkBuyOrder.OrderNo, workBestBuy + 1, m_LastWorkBuyOrder.Amount, extRef, 0, 0, 0, extRef2, out outOrderNo1, out outOrderNo2, outResMsg);
                    if (outOrderNo1 > 0)
                    {
                        m_LastWorkBuyOrder = aWorkCon.OrderDatas.GetData(outOrderNo1);
                    }
                }
            }
		}

		private void DoBuy(double price)
		{
            m_MayInBuy = true;
            string extRef = string.Empty; // m_BotSettings.WorkLogin + "_" + m_BotSettings.WorkSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
            int vol = m_NextBuyVol;
            long outOrderNo = 0;
            string outResMsg = string.Empty;
            string secBoard = m_BotSettings.WorkSecurity.SecBoard;
            string secCode = m_BotSettings.WorkSecurity.SecCode;
            if (vol > 0 && price > 0)
            {
                int res = aWorkCon.AddOrder("B", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, vol, extRef, out outOrderNo, out outResMsg);
                if (outOrderNo > 0)
                {
                    m_LastWorkBuyOrder = aWorkCon.OrderDatas.GetData(outOrderNo);
                }
                else
                    m_MayInBuy = false;
            }
            else
                m_MayInBuy = false;
		}

        private bool m_BuyHedjTime = false;
        private void HedjLastBuy(int vol)
        {
            string extRef = string.Empty; //m_BotSettings.HedjLogin + "_" + m_BotSettings.HedjSecurity.SecCode + "_" + string.Format("[{0:MM/dd/yyyy hh:mm:ss.fff}]", DateTime.Now);
            string mktLimit = "L";
            double price = (m_LastWorkBuyOrder.Price - m_NextBuyDisp) / (double)m_BotSettings.FloatKHedj;
            long outOrderNo = 0;
            string outResMsg = string.Empty;
            string secBoard = m_BotSettings.HedjSecurity.SecBoard;
            string secCode = m_BotSettings.HedjSecurity.SecCode;
            int realVol = (int)m_BotSettings.FloatKHedj / m_BotSettings.HedjSecurity.LotSize * vol;
            int res = aHedjCon.AddOrder("S", mktLimit, "S", " ", "P", " ", secBoard, secCode, "", price, realVol, extRef, out outOrderNo, out outResMsg);
            if (outOrderNo > 0)
            {
                m_LastHedjSellOrder = aHedjCon.OrderDatas.GetData(outOrderNo);
                m_BuyHedjTime = true;
            }
        }

		#endregion Расчет раздвижек

		#region Отображение данных на форме
		private void dispTimer_Tick(object sender, EventArgs e)
		{

			PerformDisp();

            this.nextSellDispLabel.Text = m_NextSellDisp.ToString();
            this.nextBuyDispLabel.Text = m_NextBuyDisp.ToString();

            if (m_HedjBestBuy < 0 || m_HedjBestSell < 0)
            {
                this.curSellDispLabel.Text = this.curBuyDispLabel.Text = "Error";
            }
            else
            {
                this.curSellDispLabel.Text = m_SellDisp.ToString();
                this.curBuyDispLabel.Text = m_BuyDisp.ToString();
            }

			this.conCountLabel.Text = m_ConCount.ToString();
            if (m_ConCount == 0)
                this.conCountLabel.BackColor = Color.Blue;
            if (m_ConCount > 0)
                this.conCountLabel.BackColor = Color.Green;
            if (m_ConCount < 0)
                this.conCountLabel.BackColor = Color.Red;

            this.hedjPosLabel.Text = m_HedjConCount.ToString();
            if (m_HedjConCount == 0)
                this.hedjPosLabel.BackColor = Color.Aqua;
            if (m_HedjConCount > 0)
                this.hedjPosLabel.BackColor = Color.Green;
            if (m_HedjConCount < 0)
                this.hedjPosLabel.BackColor = Color.Red;

            if (!m_MayInBuy && !m_MayInSell || curMode == RoboMode.rmMonitor)
                mainPanel.BackColor = m_DefCol;
            else
                if (m_MayInSell)
                    mainPanel.BackColor = Color.LightPink;
                else
                    if (m_MayInBuy)
                        mainPanel.BackColor = Color.LightGreen;
		}
		private int m_NextSellDisp = 0;
		private int m_NextBuyDisp = 0;
		private int m_NextSellVol = 0;
		private int m_NextBuyVol = 0;

		// Расчет следующих цен продажи и покупки
		private void PerformDisp()
		{
            GetConCount();

			if (m_BotSettings.IntAveraging == 0)
			{
				// раздвижки
				m_NextSellDisp = m_BotSettings.IntSellDisp;
				m_NextBuyDisp = m_BotSettings.IntBuyDisp;

				// рабочий объем
				if (m_ConCount == 0)
				{

                    if (curMode == RoboMode.rmLimitTwoWay)
                    {
                        m_NextSellVol = m_NextBuyVol = m_BotSettings.IntWorkVol;
                    }
                    if (curMode == RoboMode.rmLimitFromSell)
                    {
                        m_NextSellVol = m_BotSettings.IntWorkVol;
                        m_NextBuyVol = 0;
                    }
                    if (curMode == RoboMode.rmLimitFromBuy)
                    {
                        m_NextSellVol = 0;
                        m_NextBuyVol = m_BotSettings.IntWorkVol;
                    }
				}
				if (m_ConCount < 0)
				{
					int x = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));
					if (x < m_BotSettings.IntWorkVol) m_NextSellVol = x;
					else
						m_NextSellVol = m_BotSettings.IntWorkVol;

					int y = Math.Abs(m_ConCount);
					if (y < m_BotSettings.IntWorkVol) m_NextBuyVol = y;
					else
						m_NextBuyVol = m_BotSettings.IntWorkVol;
				}
				if (m_ConCount > 0)
				{
					int x = Math.Abs(m_ConCount);
					if (x < m_BotSettings.IntWorkVol) m_NextSellVol = x;
					else
						m_NextSellVol = m_BotSettings.IntWorkVol;

					int y = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));
					if (y < m_BotSettings.IntWorkVol) m_NextBuyVol = y;
					else
						m_NextBuyVol = m_BotSettings.IntWorkVol;
				}
			}
			else
			{
				// раздвижки
				if (m_ConCount == 0)
				{
                    if (curMode == RoboMode.rmLimitTwoWay)
                    {
                        m_NextSellDisp = m_BotSettings.IntSellDisp;
                        m_NextBuyDisp = m_BotSettings.IntBuyDisp;
                    }
                    if (curMode == RoboMode.rmLimitFromSell)
                    {
                        m_NextSellDisp = m_BotSettings.IntSellDisp;
                        m_NextBuyDisp = m_NextSellDisp - m_BotSettings.IntHotelka;
                    }
                    if (curMode == RoboMode.rmLimitFromBuy)
                    {
                        m_NextBuyDisp = m_BotSettings.IntBuyDisp;
                        m_NextSellDisp = m_NextBuyDisp + m_BotSettings.IntHotelka;
                    }

				}
				if (m_ConCount < 0)
				{
					m_NextSellDisp = m_BotSettings.IntSellDisp + Math.Abs(m_ConCount / m_BotSettings.IntPackage * m_BotSettings.IntAveraging);
					m_NextBuyDisp = m_NextSellDisp - m_BotSettings.IntHotelka;
				}
				if (m_ConCount > 0)
				{
					m_NextBuyDisp = m_BotSettings.IntBuyDisp - Math.Abs(m_ConCount / m_BotSettings.IntPackage * m_BotSettings.IntAveraging);
					m_NextSellDisp = m_NextBuyDisp + m_BotSettings.IntHotelka;
				}

				// рабочие объемы
				var curPack = Math.Abs(m_ConCount / m_BotSettings.IntPackage);
                var nextPack = (curPack + 1) * m_BotSettings.IntPackage;

				if (m_ConCount == 0)
				{
                    if (curMode == RoboMode.rmLimitTwoWay)
                    {
                        m_NextSellVol = m_NextBuyVol = m_BotSettings.IntWorkVol;
                    }
                    if (curMode == RoboMode.rmLimitFromSell)
                    {
                        m_NextSellVol = m_BotSettings.IntWorkVol;
                        m_NextBuyVol = 0;
                    }
                    if (curMode == RoboMode.rmLimitFromBuy)
                    {
                        m_NextSellVol = 0;
                        m_NextBuyVol = m_BotSettings.IntWorkVol;
                    }
				}
				if (m_ConCount < 0)
				{
					int x = Math.Abs(Math.Abs(nextPack) - Math.Abs(m_ConCount));
					int q = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));

					if (x <= m_BotSettings.IntWorkVol) m_NextSellVol = x;
					else
						if (q <= m_BotSettings.IntWorkVol) m_NextSellVol = q;
						else
							m_NextSellVol = m_BotSettings.IntWorkVol;

					int y = Math.Abs(Math.Abs(curPack) - Math.Abs(m_ConCount));
					int t = Math.Abs(m_ConCount);
					if (Math.Abs(curPack) < Math.Abs(m_ConCount) && y <= m_BotSettings.IntWorkVol) m_NextBuyVol = y;
					else
						if (t <= m_BotSettings.IntWorkVol) m_NextBuyVol = t;
						else
							m_NextBuyVol = m_BotSettings.IntWorkVol;
				}
				if (m_ConCount > 0)
				{
					int x = Math.Abs(Math.Abs(m_ConCount) - Math.Abs(curPack));
					int q = Math.Abs(m_ConCount);
                    if (Math.Abs(curPack) < Math.Abs(m_ConCount) && x <= m_BotSettings.IntWorkVol) m_NextSellVol = x;
    			    else
						if (q <= m_BotSettings.IntWorkVol) m_NextSellVol = q;
						else
							m_NextSellVol = m_BotSettings.IntWorkVol;

					int y = Math.Abs(Math.Abs(nextPack) - Math.Abs(m_ConCount));
					int t = Math.Abs(Math.Abs(m_BotSettings.IntMax) - Math.Abs(m_ConCount));
					if (y <= m_BotSettings.IntWorkVol) m_NextBuyVol = y;
					else
						if (t <= m_BotSettings.IntWorkVol) m_NextBuyVol = t;
						else
							m_NextBuyVol = m_BotSettings.IntWorkVol;
				}
			}
		}
		#endregion Отображение данных на форме

        #region Обработка клавиш
        private void mainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Escape)
            {
                if (m_MayInSell && !m_SellHedjTime)
                {
                    aWorkCon.DelOrder(m_LastWorkSellOrder.OrderNo);
                }
                if (m_MayInBuy && !m_BuyHedjTime)
                {
                    aWorkCon.DelOrder(m_LastWorkBuyOrder.OrderNo);
                }
                tradingModeComboBox.SelectedIndex = 0;
                m_MayInBuy = false;
                m_MayInSell = false;
            }
            if (e.KeyData == Keys.F1)
                tradingModeComboBox.SelectedIndex = 1;
            if (e.KeyData == Keys.F2)
                tradingModeComboBox.SelectedIndex = 2;
        }
        #endregion Обработка клавиш

    }
}
